<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
if (!function_exists('build_ranstr')) {
  /**
   * 获得随机字符串
   * @param   Number  $len    需要的长度
   * @param   Bool    $special    是否需要特殊符号
   * @return  String  返回随机字符串
   */
  function build_ranstr($len = 8, $special = false)
  {
    $chars = array(
      "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
      "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
      "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
      "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
      "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
      "3", "4", "5", "6", "7", "8", "9"
    );

    if ($special) {
      $chars = array_merge($chars, array(
        "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
        "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
        "}", "<", ">", "~", "+", "=", ",", "."
      ));
    }

    $charsLen = count($chars) - 1;
    shuffle($chars);                            //打乱数组顺序
    $str = '';
    for ($i = 0; $i < $len; $i++) {
      $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
    }
    return $str;
  }
}

if (!function_exists('build_ranstr_number')) {
  /**
   * 获得随机字符串
   * @param   Number  $len    需要的长度
   * @param   Bool    $special    是否需要特殊符号
   * @return  String  返回随机字符串
   */
  function build_ranstr_number($len = 12, $special = false)
  {
    $chars = array(
      "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
    );

    if ($special) {
      $chars = array_merge($chars, array(
        "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
        "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
        "}", "<", ">", "~", "+", "=", ",", "."
      ));
    }

    $charsLen = count($chars) - 1;
    shuffle($chars);                            //打乱数组顺序
    $str = '';
    for ($i = 0; $i < $len; $i++) {
      $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
    }
    return $str;
  }
}
if (!function_exists('build_code')) {
  function build_code($prefix = "")
  {
    @date_default_timezone_set("PRC");
    $order_id_main = date('YmdHis') . rand(10000, 99999);
    //订单号码主体长度
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for ($i = 0; $i < $order_id_len; $i++) {
      $order_id_sum += (int)(substr($order_id_main, $i, 1));
    }
    //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
    $osn = $prefix . $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
    return $osn;
  }
}

if (!function_exists('build_id')) {
  function build_id($prefix = "")
  {
    @date_default_timezone_set("PRC");
    $order_id_main = date('YmdHi') . rand(1, 10);
    //订单号码主体长度
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for ($i = 0; $i < $order_id_len; $i++) {
      $order_id_sum += (int)(substr($order_id_main, $i, 1));
    }
    //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
    $osn = $prefix . $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
    return $osn;
  }
}

if (!function_exists('upload')) {
  /**
   * @param String $name 图片的字段名
   * @param String $path 保存路径
   * @return Array 返回结果
   */
  function upload($name, $path = 'uploads')
  {
    // TODO 获取表单上传文件 =>类似原生里的 $_FILES
    $file = request()->file($name);

    // TODO 移动到框架应用根目录/public/uploads/ 目录下
    if ($file) {
      $path = ROOT_PATH . '/public/' . $path;

      $info = $file->move($path);

      if ($info) {
        $filename = $info->getSaveName();

        $filename = str_replace('\\', '/', '/uploads/' . $filename);

        return ['code' => 1, 'msg' => '上传成功', 'data' => $filename];
      } else {
        return ['code' => 0, 'msg' => $file->getError(), 'data' => null];
      }
    }

    return false;
  }
}

if (!function_exists('CommentTree')) {
  //创建一个公共函数，来处理评论的递归  处理数据
  /**
   * @param list 评论数据
   * @param pid 评论上一级id
   * @param User 用户
   */
  function CommentTree($list, $pid = 0, $User)
  {
    // 定义空的数组
    $data = [];

    if ($list) {
      // 循环评论数据
      foreach ($list as $item) {
        // 评论里的点赞字段不为空
        if (!empty($item['like'])) {
          //字符串转数组
          $LikeArr = explode(',', $item['like']);
          $LikeArr = array_filter($LikeArr);  //去除数组中的空元素
          // 获取点赞的总数
          $LikeCount = is_array($LikeArr) ? count($LikeArr) : 0;

          // 自定义一个数据表不存在的字段
          $item['like_count'] = $LikeCount;

          //判断当前这一条评论是不是本人点过赞
          // $user['id']
          // $LikeArr
          // echo $User['id'];
          // if(in_array($User['id'],$LikeArr)) echo 111;
          // halt($LikeArr);
          if (in_array($User['id'], $LikeArr)) {
            // 点过赞
            // echo 111;
            // exit;
            $item['active'] = true;
          } else {
            // echo 11;
            // exit;
            $item['active'] = false;
          }
        } else {
          //当like字段为空
          $item['like_count'] = 0;
        }

        //id = 1 pid = 0
        if ($item['pid'] == $pid) {
          //找出相等pid值，给当前的评论新增一个自定义属性
          //递归找子集
          $item['child'] = CommentTree($list, $item['id'], $User);
          $data[] = $item;
        }
      }
    }

    return $data;
  }
}

if (!function_exists('CommentHtml')) {
  //处理递归循环输出  处理输出
  /**
   * @param list 评论数据
   * @param post 当前帖子数据
   * @param flag 是否为父级评论
   * @return output 返回递归数据
   */
  function CommentHtml($LoginUser, $list, $post, $flag = 'top', $output = "")
  {
    // $output = "";
    foreach ($list as $key => $item) {
      // 外边距
      $PaddingLeft = $item['level'] * 1;

      $output .= "<li style='padding-left:{$PaddingLeft}em' class='jieda-daan'>";
      // 头像
      $output .= "<div class='detail-about detail-about-reply'>";
      // 头像
      $url = url('home/user/index', ['userid' => $item['userid']]);
      $output .= "<a class='fly-avatar' href='$url'>";

      //判断头像
      if (is_file('.' . $item['user']['avatar'])) {
        $avatar = $item['user']['avatar'];
        $output .= "<img src='$avatar' />";
      } else {
        $output .= "<img src='/static/home/res/images/avatar/default.png' />";
      }
      $output .= "</a>";


      // 用户信息
      $output .= "<div class='fly-detail-user'>";
      $output .= "<a href='javascript:void(0)' class='fly-link'>";
      $nickname = $item['user']['nickname'];
      $output .= " <cite>$nickname</cite>";

      if ($item['user']['auth'] > 0) {
        $output .= "<i class='iconfont icon-renzheng'></i>";
      }
      $output .= "</a>";

      // 楼主
      if ($flag == 'top') {
        $output .= "<span style='color:#FF7200'>(楼主)</span>";
      }

      // 判断是否为发帖人
      if ($item['userid'] == $post['userid']) {
        $output .= "<span style='color:#5FB878'>(发帖人)</span>";
      }
      $output .= "</div>";

      // 评论时间
      $output .= "<div class='detail-hits'>";
      $output .= "<span>{$item['createtime']}</span>";
      $output .= "</div>";


      // 采纳图标
      if ($item['accept'] == 1) {
        $output .= "<i class='iconfont icon-caina' title='最佳答案'></i>";
      }
      $output .= "</div>";

      // 评论内容
      $output .= "<div class='detail-body jieda-body photos'>";
      $output .= "<p>{$item['content']}</p>";
      $output .= "</div>";

      // 回复
      if (cookie('LoginUser')) {
        $output .= "<div class='jieda-reply'>";

        // halt()
        // 点赞
        if (!empty($item['active'])) {
          $output .= "<span class='jieda-zan zanok' data-id='{$item['id']}' type='zan'>";
        } else {
          $output .= "<span class='jieda-zan' data-id='{$item['id']}' type='zan'>";
        }


        $output .= "<i class='iconfont icon-zan'></i>";
        $output .= "<em class='likeCount'>{$item['like_count']}</em>";
        $output .= "</span>";

        // 回复
        if (!$post['accept']) {
          $pid = $item['id'];
          $nickname2 = $item['user']['nickname'];
          $output .= "<a href='#comment' class='reply' type='reply' data-pid='$pid' data-nickname='$nickname2'>";
          $output .= "<i class='iconfont icon-svgmoban53'></i>\r\n回复";
          $output .= "</a>";
        }
        $output .= "<div class='jieda-admin'>";
        // (登录的人 == 发帖userid)发帖人  || 评论本人（评论人 == 登录的人）

        $userid = isset($LoginUser['id']) ? $LoginUser['id'] : 0;
        if ($userid == $post['userid'] || $userid == $item['userid']) {
          if (!$post['accept']) {
            $output .= "<span type='del' class='delComment' data-id='{$item['id']}'>删除</span>";
          }
        }

        // 登录用户 == 发帖人 => 给采纳图标
        if ($userid == $post['userid']  && $item['userid'] != $userid) {
          if (!$post['accept']) {
            $output .= "<span class='accept' data-comid='{$item['id']}' class='jieda-accept' type='accept'>";
            $output .= "采纳";
            $output .= "</span>";
          }
        }
        $output .= "</div>";


        $output .= "</div>";
      }
      $output .= "</li>";

      //判断是否有子集
      if (!empty($item['child'])) {
        $output = CommentHtml($LoginUser, $item['child'], $post, 'son', $output);
      }
    }

    return $output;
  }
}

if (!function_exists('CommentDelete')) {
  /**
   * @param commentList 帖子评论数据
   * @param comid 当前点击的评论数据id
   */
  $data = [];
  function CommentDelete($commentList, $comid)
  {
    global $data;
    // $data = [];
    // foreach ($commentList as $item) {
    //   echo 'id =>'.$item['id'].' pid =>'.$item['pid'].'<br>';
    // }
    // exit;
    foreach ($commentList as $item) {
      // TODO 判断当前id的pid值等于comid
      if ($item['pid'] == $comid) {
        $data[] = $item['id'];
        // TODO 子评论下面可能还有子评论 就用递归方式实现
        CommentDelete($commentList, $item['id']);
      }
    }
    // halt($data);
    return $data;
  }
}

if (!function_exists('ListHtml')) {
  /**
   * @param data 接收数据
   * @param url 编辑路径
   * @return output 返回数据
   */
  function ListHtml($data, $url, $output = "")
  {
    foreach ($data as $item) {
      $id = $item['id'];
      $username = $item['username'];
      $nickname = $item['nickname'];
      $state = $item['state'];
      $state_text = $item['state_text'];
      $stateShow = $state == 1 ? 'badge-success' : 'badge-warning';

      $output .= "<tr><td><div class='custom-control custom-checkbox'><input type='checkbox' class='custom-control-input ids' name='ids[]' value='{$id}' id='ids-{$id}' />";
      $output .= "<label class='custom-control-label' for='ids-{$id}'></label></div></td>";

      $output .= "<td>{$id}</td>";
      $output .= "<td>{$username}</td>";
      $output .= "<td>{$nickname}</td>";
      $output .= "<td style='font-size: 18px'>";
      $output .= "<span class='badge {$stateShow}'>{$state_text}</span></td>";
      $output .= "<td><div class='btn-group'><a class='btn btn-xs btn-default' ";

      $url = url($url, ['id' => $id]);

      $output .= "href='$url'";

      $output .= " data-toggle='tooltip' data-original-title='编辑'><i class='mdi mdi-pencil'></i></a>";

      $output .= "<a class='btn btn-xs btn-default del' data-original-title='删除' href='javascript:;' data-toggle='tooltip' data-id='{$id}'><i class='mdi mdi-window-close'></i></a></div></td></tr>";
      // $output .= "</tr>";
    }
    return $output;
  }
}

if (!function_exists('ContentTemp')) {
  /**
   * @param Array data 接收数据
   * @return output 返回数据
   */
  function ContentTemp($data, $output = "")
  {
    $output = '';
    foreach ($data as $item) {
      $output .= "<li>{$item}</li>";
    }

    return $output;
  }
}
